<template>
  <div :name="name" v-if="read">
      <input type="file" name="file" @change="change()" style="display:none;" :accept="fileType.join()" />
  </div>
</template>
<script type="text/ecmascript-6">
  export default {
    props: {
      index: {
        type: Number
      },
      fileType: {
        type: Array
      },
      namelog: {
        type: String
      }
    },
    data () {
      return {
        fileName: '',
        content: '',
        read: true
      }
    },
    computed: {
      name: function () {
        return this.namelog + this.index
      }
    },
    mounted () {
      document.getElementsByName(this.name)[0].firstChild.click()
    },
    methods: {
      change () {
        if (!window.FileReader) {
          alert('Not supported by your browser!')
          return
        }
        // alert(JSON.stringify(this.fileType))
        var fileup = this
        var s = false
        var file = document.getElementsByName(this.name)[0].firstChild
        var reader = new window.FileReader()
        reader.onloadstart = function () {
          for (var i = 0; i < fileup.fileType.length; i++) {
            if (file.files[0].name.substring(file.files[0].name.lastIndexOf('.'), file.files[0].name.length) === fileup.fileType[i]) {
              s = true
            }
          }
          // 这个事件在读取开始时触发
          console.log('onloadstart')
        }
        reader.onprogress = function (p) {
            // 这个事件在读取进行中定时触发
          console.log('onprogress')
        }
        reader.onload = function () {
          this.read = true
          // 这个事件在读取成功结束后触发
          console.log('load complete')
          console.log('onloadend')
          fileup.fileName = encodeURIComponent(file.files[0].name)
          fileup.content = reader.result
          // fileup.$emit('listenToChildEvent', JSON.stringify({fileName:fileup.fileName,content:fileup.content}}))
          fileup.$emit('listenToChildEvent', {index: fileup.index, fileName: fileup.fileName, content: fileup.content, upload: s})
        }
        reader.onloadend = function () {
          // alert('cccccccc')
          // this.data.push(reader.result)
          console.log('onloadend')
          // console.log(reader.result)
          // fileup.fileName = encodeURIComponent(file.files[0].name)
          // fileup.content = reader.result
          // alert(this.content)
          // fileup.$emit('listenToChildEvent', JSON.stringify({fileName:fileup.fileName,content:fileup.content}}))
          // fileup.$emit('listenToChildEvent', {index: fileup.index, fileName: fileup.fileName, content: fileup.content, upload: s})
        }
        reader.readAsDataURL(file.files[0])
      }
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">

</style>
